import { storeManager } from "@/store";
import { HeadersType, HttpRequest } from "@/http";

const filterData = (arr: Array<any>): Array<any> => {
	if (!arr || !arr.length) return [];
	return arr.map((v: any) => {
		return {
			label: v.name,
			value: v.code,
			id: v.id,
			children: filterData(v.children),
		};
	});
};

export const getAddress = async (msg?: any[]) => {
	let arr: any[] = [];
	await dictService.getsystemSites(msg).then(res => {
		if (msg?.length === 3 || msg?.length === 4) {
			res &&
				res?.children?.forEach((i: any) => {
					arr.push({
						label: i.name,
						value: i.code,
						id: i.id,
					});
				});
			// }
		} else if (msg?.length === 5 || msg?.length === 6) {
			res &&
				res?.children?.forEach((i: any) => {
					arr.push({
						label: i.name,
						value: i.code,
						id: i.id,
						leaf: true,
					});
				});
		} else {
			res &&
				res?.children?.forEach((i: any, k: number) => {
					if (k !== 0) {
						i.children.forEach((ii: any) => {
							arr.push({
								label: ii.name,
								value: ii.code,
								id: ii.id,
							});
						});
					}
				});
		}
	});
	return arr;
};

class DictService {
	private CACHE_DICT = "CACHE_DICT";
	private CACHE_SYSTEM_SITES = "CACHE_SYSTEM_SITES";
	private cache = storeManager.register("systemSites");

	/**
	 * 字典模型
	 * @param Codes
	 * @returns
	 */
	public async getDict(Codes: any[]): Promise<any> {
		const data = this.cache.get(this.CACHE_DICT + (Codes.toString() || "")).data || {};
		if (Object.keys(data)?.length) {
			return data;
		}

		const result = await new HttpRequest(`/system/dict`, {
			header: HeadersType.Urlencoded,
		}).get({
			modelCodes: Codes.toString(),
		});

		if (result && result.success && result.data) {
			this.cache.set(this.CACHE_DICT + (Codes?.toString() || ""), {
				data: result.data,
			});
			return result.data;
		} else {
			return undefined;
		}
	}

	/**
	 * 获取站点
	 * 传入codes精确查找
	 * 不传查全部站点
	 * @param Codes
	 * @returns
	 */
	public async getsystemSites(Codes?: any[]): Promise<any> {
		const data =
			this.cache.get(this.CACHE_SYSTEM_SITES + (Codes?.toString() || ""))?.data || {};

		if (Object.keys(data)?.length) {
			return data;
		}
		let result = await new HttpRequest(`/system/sites`, {
			header: HeadersType.Urlencoded,
		}).get({
			siteCodes: Codes ? Codes.toString() : null,
			// siteCodes: ""
		});

		if (result && result.data && result.success) {
			this.cache.set(this.CACHE_SYSTEM_SITES + (Codes?.toString() || ""), {
				data: result.data,
			});

			return result.data;
		} else {
			return undefined;
		}
	}
	getAddress() {
		const data = this.cache.get(this.CACHE_SYSTEM_SITES)?.data || {};
		if (Object.keys(data)?.length) {
			return filterData(data?.children);
		} else {
			return [];
		}
	}
}

const dictService = new DictService();
export { dictService };
